<!DOCTYPE html
	PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>百度地图API-批量地址解译</title>
    <link href="css/Baidu.css" rel="stylesheet" type="text/css" />
</head>

<body tabindex="1" id="body">
    <div id="head">
        城市名称：<input id="city" />
        <input type="button" onclick="setCity()" id="setcity" value="定位"></input>
        | 经度：
        <input id="long" value="111"></input>
        纬度：<input id="lat" value="33"></input>
        <input type="button" onclick="setLatLonPosition()" id="setllpo" value="定位"></input>
        <input type="button" onclick="getPOI()" id="getpoi" value="获取POI"></input>
        <input type="button" onclick="getImage()" id="getpoi" value="获取截图"></input>
        <a id="down1" class="down1" href="" download="downImg">
            <span id="downImg"></span>
        </a>
        <input type="text" id="info" style="width: 300px;"></input>
        <br /> 打开Excel：
        <input type="file" id="open-excel"></diid=>
        <input type="button" onclick="getallPOI()" id="bdgeo" value="获取所有POI"></input>
        <input type="button" onclick="setAllPosition()" id="addmarker" value="定位"></input>
        <input type="button" onclick="getallImage()" id="bdgeo" value="获取所有截图"></input>
        导出Excel： 选择路径:

        <input type="button" onclick="javascript:exportExcel('我的文件')" id="addmarker" value="导出Excel"></input>
        <!-- <input id="Button1" type="button" value="导出EXCEL" onclick="javascript:table2excel('test','我的文件')" /> -->
    </div>
    <div id="l-map" class="l-map"></div>
    <div class="uploadImg" id="uploadImg">
    </div>

    <div class="open" id="open">
    </div>
</body>

</html>
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="js/import.js"></script>
<script type="text/javascript" src="js/export.js"></script>
<script type="text/javascript" src="js/mymap.js"></script>
<!-- <script type="text/javascript" src="js/canvas2image.js"></script> -->
<!-- <script type="text/javascript" src="js/xlsx.core.min.js"></script> -->
<script src="https://cdn.bootcss.com/xlsx/0.11.9/xlsx.core.min.js"></script>
<script src="http://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<!-- https://cdn.bootcss.com/xlsx/0.12.7/xlsx.js -->
<script type="text/javascript" src="http://api.map.baidu.com/api?v=1.4&ak=PPDuSsbu2kdqP0o7WzvXQn1dB0NNzu4l"></script>
<script type="text/javascript" src="http://api.map.baidu.com/api?type=webgl&v=1.0&ak=PPDuSsbu2kdqP0o7WzvXQn1dB0NNzu4l"></script>
<script type="text/javascript">
    initMap();
    var values; // 存储获取到的数据
    var mypoints = []; //存储纠偏后的values对应点
    var index = 0; //批量获取POI循环
    var pIndex = 0; //批量处理数据点偏移循环
    var i = 0; //批量下载图片循环
    //坐标转换完之后的回调函数
    //读取表格文件内容
    $('#open-excel').change(function(e) {
        values = [];
        var files = e.target.files;
        var fileReader = new FileReader();
        fileReader.readAsBinaryString(files[0]); // 以二进制方式打开文件
        fileReader.onload = function(ev) {
            try {
                var data = ev.target.result,
                    workbook = XLSX.read(data, {
                        type: 'binary'
                    }),
                    value
                    // values = []; 
            } catch (e) {
                console.log('文件类型不正确');
                return;
            }

            // 遍历每张表读取
            for (var sheet in workbook.Sheets) {
                if (workbook.Sheets.hasOwnProperty(sheet)) {
                    // 得到表数据并转成json格式
                    let xlsxData = XLSX.utils.sheet_to_json(workbook.Sheets[sheet], {
                        defval: '',
                        raw: false,
                        cellDates: true
                    });
                    values = values.concat(xlsxData);
                    //处理坐标，百度的偏移问题
                    getallPoint();
                    // values = values.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                    break; // 如果只取第一张表，加上这行
                }
            }
        }

    });

    //偏移坐标转换的迭代函数
    function getallPoint() {
        getPoint(pIndex);
        pIndex++;
    }
    //处理表格中大量数据，将坐标转换成非偏移坐标
    function getPoint(pIndex) {
        var convertor = new BMapGL.Convertor();

        var total = values.length;
        //获取经纬度值
        var x = values[pIndex].lon;
        var y = values[pIndex].lat;
        if (x != '' && y != '') {
            var ggPoint = new BMapGL.Point(x, y);
            var pointArr = [];
            pointArr.push(ggPoint);
            //纠偏处理
            convertor.translate(pointArr, COORDINATES_WGS84, COORDINATES_BD09, function(data) {
                if (data.status === 0) {
                    //存数据
                    mypoints[pIndex] = data.points;
                    // mypoints[pIndex]["lon"] = data.points.lon;
                    if (pIndex == values.length - 1) {
                        var html = json2Html(values);
                        //pIndex为0，为下次数据做准备。
                        pIndex = 0;
                        alert("数据处理完成");
                    }
                }
            })
        }
        if (pIndex < values.length - 1) {
            //循环的核心
            setTimeout(window.getallPoint, 20);
        }
    }
    //6000多条数据，1分56秒

    //获取POI的迭代函数
    function getallPOI() {
        getPOI3(values, mypoints, index);
        index++;
    }
    //获取表格中大量数据的POI，并渲染到页面
    function getPOI3(mydata, mypoints, index) {
        var indexObj = {};
        var description = '';
        if (mypoints[index] != undefined) {
            //获取经纬度
            var lon = parseFloat(mypoints[index][0].lng.toFixed(6));
            var lat = parseFloat(mypoints[index][0].lat.toFixed(6));
            var pt = new BMap.Point(lon, lat);
            //为异步处理数据数据时准确地找到数据
            if (pt) {
                var key = "" + pt.lng + pt.lat;
                indexObj[key] = index;
            }
            var geocoder = new BMap.Geocoder();
            var locationOptions = {
                poiRadius: 1500,
                numPois: 2
            }
            description = geocoder.getLocation(pt, function(result) {
                    //获取POI信息
                    if (result) {
                        //当前坐标的下标
                        var cKey = '' + result.point.lng + result.point.lat;
                        var cIndex = indexObj[cKey]; //当前的index
                        //获取位置信息
                        description = result.address;
                        if (result.surroundingPois[0]) {
                            var poi = result.surroundingPois[0];
                            description += "，" +
                                poi.title + getDirDescription2(result.point, poi.point) + " " +
                                Math.round(map.getDistance(result.point, poi.point)) + "米，"
                        }
                        if (result.surroundingPois[1]) {
                            var poi = result.surroundingPois[1];
                            description += "" +
                                poi.title + getDirDescription2(result.point, poi.point) + " " +
                                Math.round(map.getDistance(result.point, poi.point)) + "米。"
                        }
                        //将位置信息存放进数据库
                        mydata[cIndex]["address"] = description
                        if (index == mydata.length - 1) {
                            //展示到页面
                            json2Html(mydata);
                            //更新数据，为后续处理做准备
                            values = mydata;
                            index = 0;
                            alert("地址加载处理完成");
                        }
                    }
                },
                locationOptions);
            if (index < mydata.length - 1) {
                //循环的核心
                setTimeout(window.getallPOI, 20);
            }
        }
    }
    //对表格中出现的所有经纬度进行定位
    function setAllPosition() { //参数：经纬度

        map.clearOverlays();
        for (var i = 0; i < mypoints.length; i++) {
            //获取经纬度
            var lon = parseFloat(mypoints[i][0].lng.toFixed(6));
            var lat = parseFloat(mypoints[i][0].lat.toFixed(6));
            var point = new BMap.Point(lon, lat);
            //设置中心点
            if (i == mypoints.length - 1) {
                map.centerAndZoom(point, 15);
            }
            var marker = new BMap.Marker(point);
            // var info = "经度：" + lon + ";纬度：" + lat;
            // marker.setLabel(info);
            map.addOverlay(marker);

            var info = "经度：" + values[i].lon + ";纬度：" + values[i].lat;
            var label = new BMap.Label(info, {
                offset: new BMap.Size(10, -10)
            });
            marker.setLabel(label); //添加百度label
        }

    }

    //使用城市名进行定位
    function setCity() { //参数：城市名
        var cityname = document.getElementById("city").value;
        map.centerAndZoom(cityname, 15);
    }


    function getImage(imageName) {
        var canvas = document.getElementById("l-map");
        var width = canvas.offsetWidth; //dom宽
        var height = canvas.offsetHeight; //dom高
        if (imageName == null) {
            var imageName = 'download.png';
        }
        var imgName = imageName;
        html2canvas(canvas, {
            scale: 2, //缩放比例,默认为1
            allowTaint: false, //是否允许跨域图像污染画布
            // foreignObjectRendering: true,
            useCORS: true, //是否尝试使用CORS从服务器加载图像
            width: width, //画布的宽度
            height: height, //画布的高度
        }).then((canvas) => {
            //将canvas转为base64格式
            var imgUri = canvas.toDataURL("image/png"); //图片格式
            // 把url放到我们的a标签中，并得到a标签对象
            // var triggerHref = $("#saveImg").attr("href", imgUri).attr("download" + '.png');
            $("#down1").attr("href", imgUri);
            $("#down1").attr("download", imgName);
            // triggerDownload.click(); //模拟点击！
            document.getElementById("downImg").click();
        });
        if (imageName != null) {
            i++;
            if (i < mypoints.length) {
                setTimeout(getallImage(i), 10000);
            }
        }
    }


    function getallImage() {
        // for (var i = 0; i < mypoints.length; i++) {
        var lon = parseFloat(mypoints[i][0].lng.toFixed(6));
        var lat = parseFloat(mypoints[i][0].lat.toFixed(6));
        setLatLonPosition(lon, lat);
        var imageName = values[i].tbbh + '.jpg'
        setTimeout(getImage(imageName), 10000);

        // }

    }
    //使用经纬度进行定位
    function setLatLonPosition(x, y) { //参数：经纬度
        if (x == undefined && y == undefined) {
            var x = document.getElementById("long").value;
            var y = document.getElementById("lat").value;
            var convertor = new BMapGL.Convertor();
            // var point = '';
            if (x != '' && y != '') {
                var ggPoint = new BMapGL.Point(x, y);
                var pointArr = [];
                pointArr.push(ggPoint);
                //纠偏并定位
                convertor.translate(pointArr, COORDINATES_WGS84, COORDINATES_BD09, function(data) {
                    if (data.status === 0) {
                        var lon = parseFloat(data.points[0].lng.toFixed(6));
                        var lat = parseFloat(data.points[0].lat.toFixed(6));
                        var point = new BMap.Point(lon, lat);

                        map.centerAndZoom(point, 15);
                        map.clearOverlays();
                        // map.addOverlay(new BMap.Marker(point));

                        var marker = new BMap.Marker(point);
                        map.addOverlay(marker);
                        var info = "经度：" + x + ";纬度：" + y;
                        var label = new BMap.Label(info, {
                            offset: new BMap.Size(10, -10)
                        });
                        marker.setLabel(label); //添加百度label
                    }
                })
            }
        } else {
            var lon = x;
            var lat = y;
            var point = new BMap.Point(lon, lat);

            map.centerAndZoom(point, 15);
            map.clearOverlays();
            // map.addOverlay(new BMap.Marker(point));

            var marker = new BMap.Marker(point);
            map.addOverlay(marker);
            // var info = "经度：" + x + ";纬度：" + y;
            // var label = new BMap.Label(info, {
            //     offset: new BMap.Size(10, -10)
            // });
            // marker.setLabel(label); //添加百度label
        }

    }
    //单个点的获取POI
    function getPOI() {
        var x = document.getElementById("long").value;
        var y = document.getElementById("lat").value;
        var convertor = new BMapGL.Convertor();
        // var point = '';
        if (x != '' && y != '') {
            var ggPoint = new BMapGL.Point(x, y);
            var pointArr = [];
            pointArr.push(ggPoint);
            // 纠偏
            convertor.translate(pointArr, COORDINATES_WGS84, COORDINATES_BD09, function(data) {
                if (data.status === 0) {
                    var lon = parseFloat(data.points[0].lng.toFixed(6));
                    var lat = parseFloat(data.points[0].lat.toFixed(6));
                    var pt = new BMap.Point(lon, lat);
                    var geocoder = new BMap.Geocoder();
                    var locationOptions = {
                        poiRadius: 1500,
                        numPois: 2
                    }

                    var description = '';
                    // 根据经纬度获取POI
                    var description = geocoder.getLocation(pt, function(result) {
                        if (result) {
                            description = result.address;
                            if (result.surroundingPois[0]) {
                                var poi = result.surroundingPois[0];
                                description += "，" +
                                    poi.title + getDirDescription2(result.point, poi.point) + " " +
                                    Math.round(map.getDistance(result.point, poi.point)) + "米，"
                            }
                            if (result.surroundingPois[1]) {
                                var poi = result.surroundingPois[1];
                                description += "" +
                                    poi.title + getDirDescription2(result.point, poi.point) + " " +
                                    Math.round(map.getDistance(result.point, poi.point)) + "米。"
                            }

                            var info = document.getElementById("info");
                            info.setAttribute("value", description);
                        }
                    }, locationOptions);

                }
            })
        }



    }
</script>